package com.example.g7640.util;

import com.example.g7640.dto.SessionDto;
import com.example.g7640.enums.UserType;
import com.example.g7640.exception.BizException;

public class RoleCheckUtil {


    public static void checkAdmin(){
        SessionDto session = SessionLocal.getSession();
        if(session == null){
            throw new BizException("privilege anomaly");
        }
        if(!UserType.admin.equal(session.getType())){
            throw new BizException("You do not have permission to access");
        }
    }


    public static void checkCustomer(){
        SessionDto session = SessionLocal.getSession();
        if(session == null){
            throw new BizException("privilege anomaly");
        }
        if(!UserType.customer.equal(session.getType())){
            throw new BizException("You do not have permission to access");
        }
    }


    public static void checkVendor(){
        SessionDto session = SessionLocal.getSession();
        if(session == null){
            throw new BizException("privilege anomaly");
        }
        if(!UserType.vendor.equal(session.getType())){
            throw new BizException("You do not have permission to access");
        }
    }


    public static void check(UserType ... userTypes){
        if(userTypes == null || userTypes.length == 0){
            throw new BizException("No roles are passed");
        }
        SessionDto session = SessionLocal.getSession();
        if(session == null){
            throw new BizException("authority anomaly");
        }
        boolean hasRole = false;
        for (UserType userType : userTypes) {
            if(userType.equal(session.getType())){
                hasRole = true;
                break;
            }
        }
        if(!hasRole){
            throw new BizException("You do not have permission to access");
        }
    }
}
